<template>
  <div class="defect-basic-page">
    <el-card class="card-block breadcrumb-card">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>质量管理</el-breadcrumb-item>
        <el-breadcrumb-item>缺陷管理</el-breadcrumb-item>
        <el-breadcrumb-item>缺陷等级</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card class="filter-card card-block">
      <el-form :inline="true" :model="queryForm" label-width="auto">
        <el-form-item label="等级编号">
          <el-input v-model="queryForm.defectlevelcard" placeholder="请输入等级编号" clearable />
        </el-form-item>
        <el-form-item label="等级名称">
          <el-input v-model="queryForm.defectlevelname" placeholder="请输入等级名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.defectlevelstate" placeholder="请选择状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table-card card-block">
      <div class="toolbar">
        <el-button type="primary" @click="openDialog('create')">新增</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">删除</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="70" />
        <el-table-column prop="defectlevelcard" label="等级编号" min-width="120" />
        <el-table-column prop="defectlevelname" label="等级名称" min-width="150" />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.defectlevelstate === '启用' ? 'success' : 'info'">
              {{ row.defectlevelstate }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="defectleveldes" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="openDialog('edit', row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :total="pagination.totalCount"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="520px" @close="handleDialogClose">
      <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px">
        <el-form-item label="等级编号" prop="defectlevelcard">
          <el-input v-model="formModel.defectlevelcard" placeholder="请输入等级编号" />
        </el-form-item>
        <el-form-item label="等级名称" prop="defectlevelname">
          <el-input v-model="formModel.defectlevelname" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="状态" prop="defectlevelstate">
          <el-radio-group v-model="formModel.defectlevelstate">
            <el-radio-button label="启用" />
            <el-radio-button label="禁用" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="defectleveldes">
          <el-input v-model="formModel.defectleveldes" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { reactive, ref, computed, onMounted } from "vue";
import https from "@/Http/http";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";

type ApiEnum = -1 | 0 | 1;

interface ApiPageingResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T;
}

interface DefectLevelDTO {
  id: number;
  defectlevelcard: string;
  defectlevelname: string;
  defectlevelstate: string;
  defectleveldes: string;
}

interface DefectLevelRow extends DefectLevelDTO {
  index: number;
}

const loading = ref(false);
const tableData = ref<DefectLevelRow[]>([]);
const multipleSelection = ref<DefectLevelRow[]>([]);

const statusOptions = [
  { label: "启用", value: "启用" },
  { label: "禁用", value: "禁用" },
];

const queryForm = reactive({
  defectlevelcard: "",
  defectlevelname: "",
  defectlevelstate: "",
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const dialogVisible = ref(false);
const dialogMode = ref<"create" | "edit">("create");
const formRef = ref<FormInstance>();
const formModel = reactive({
  id: undefined as number | undefined,
  defectlevelcard: "",
  defectlevelname: "",
  defectlevelstate: "启用",
  defectleveldes: "",
});

const rules: FormRules = {
  defectlevelcard: [{ required: true, message: "请输入等级编号", trigger: "blur" }],
  defectlevelname: [{ required: true, message: "请输入等级名称", trigger: "blur" }],
};

const dialogTitle = computed(() =>
  dialogMode.value === "create" ? "新增缺陷等级" : "编辑缺陷等级",
);

const fetchTableData = async () => {
  loading.value = true;
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<DefectLevelDTO>>("/Defect/DefectLevel", {
      params: {
        pagesize: pagination.pageSize,
        pageindex: pagination.pageIndex,
        defectlevelcard: queryForm.defectlevelcard,
        defectlevelname: queryForm.defectlevelname,
        defectlevelstate: queryForm.defectlevelstate,
      },
    });
    if (data.code !== 1) {
      throw new Error(data.msg || "查询失败");
    }
    pagination.totalCount = data.totalCount || 0;
    tableData.value = (data.data || []).map((item, index) => ({
      ...item,
      index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1,
    }));
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || "获取缺陷等级失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.defectlevelcard = "";
  queryForm.defectlevelname = "";
  queryForm.defectlevelstate = "";
  handleQuery();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchTableData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page;
  fetchTableData();
};

const handleSelectionChange = (rows: DefectLevelRow[]) => {
  multipleSelection.value = rows;
};

const resetForm = () => {
  formRef.value?.resetFields();
  formModel.id = undefined;
  formModel.defectlevelstate = "启用";
  formModel.defectleveldes = "";
};

const openDialog = (mode: "create" | "edit", row?: DefectLevelRow) => {
  dialogMode.value = mode;
  if (mode === "edit" && row) {
    formModel.id = row.id;
    formModel.defectlevelcard = row.defectlevelcard;
    formModel.defectlevelname = row.defectlevelname;
    formModel.defectlevelstate = row.defectlevelstate;
    formModel.defectleveldes = row.defectleveldes;
  } else {
    resetForm();
  }
  dialogVisible.value = true;
};

const handleDialogClose = () => {
  resetForm();
};

const buildPayload = () => ({
  id: formModel.id,
  defectlevelcard: formModel.defectlevelcard,
  defectlevelname: formModel.defectlevelname,
  defectlevelstate: formModel.defectlevelstate,
  defectleveldes: formModel.defectleveldes,
});

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    try {
      const payload = buildPayload();
      const request =
        dialogMode.value === "create"
          ? https.Writes.post<ApiResultResponse<number>>("/CommonDefects/DefectLevelAddCommands", payload)
          : https.Writes.put<ApiResultResponse<number>>("/CommonDefects/DefectLevelUpdateCommands", payload);
      const { data } = await request;
      if (data.code !== 1) {
        throw new Error(data.msg || "保存失败");
      }
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      fetchTableData();
    } catch (error: any) {
      console.error(error);
      ElMessage.error(error.message || "保存失败");
    }
  });
};

const deleteDefectLevel = (id: number) =>
  https.Writes.request<ApiResultResponse<number>>({
    method: "delete",
    url: "/CommonDefects/DefectLevelDelCommands",
    data: { id },
  });

const handleDelete = (row: DefectLevelRow) => {
  ElMessageBox.confirm(`确认删除等级【${row.defectlevelname}】吗？`, "提示", { type: "warning" })
    .then(async () => {
      try {
        const res = await deleteDefectLevel(row.id);
        if (res.data.code !== 1) {
          throw new Error(res.data.msg || "删除失败");
        }
        ElMessage.success("删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条数据吗？`, "提示", { type: "warning" })
    .then(async () => {
      try {
        await Promise.all(
          multipleSelection.value.map((item) =>
            deleteDefectLevel(item.id),
          ),
        );
        ElMessage.success("批量删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "批量删除失败");
      }
    })
    .catch(() => {});
};

onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
.defect-basic-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: linear-gradient(135deg, #f3f5ff 0%, #fef5f5 45%, #fdf8ff 100%);
}

.filter-card,
.table-card,
.card-block {
  width: 100%;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.88), rgba(237, 244, 255, 0.8));
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
  backdrop-filter: blur(12px);
  border-radius: 12px;
}

.toolbar {
  margin-bottom: 12px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>

